import { Repository } from 'typeorm';
import { ArticleEntity, NewArticleEntity } from './ArticleEntity';
import { ArticlesRepository } from './ArticlesRepository';
import { AppDataSource } from '../../data-source'; // 导入全局 DataSource

// extends Repository<ArticleEntity>
export class ArticlesRepositoryImpl implements ArticlesRepository {
  private repository: Repository<ArticleEntity>;

  constructor() {
    this.repository = AppDataSource.getRepository(ArticleEntity);
  }

  async fetchOneById(id: string): Promise<ArticleEntity | undefined> {
    const article = await this.repository.findOne({ where: { id } });
    if (!article) {
      throw new Error(`Article with id ${id} not found`);
    }
    return article;
  }

  async createArticle(article: NewArticleEntity): Promise<ArticleEntity> {
    const newArticle = this.repository.create(article);
    return this.repository.save(newArticle);
  }
}